#!/bin/bash

# Function to fetch problem details from Codeforces
fetch_problem_details() {
    local url=$1
    # Extract problem ID from URL
    local problem_id=$(echo $url | grep -oP '(?<=problem/)\d+/[A-Z]')
    # Fetch the problem page content
    local problem_page=$(curl -s $url)
    # Extract the title of the problem
    local title=$(echo "$problem_page" | grep -oP '(?<=<div class="title">).*(?=</div>)')
    # Extract the difficulty of the problem
    local difficulty=$(echo "$problem_page" | grep -oP '(?<=<span class="tag-box" title="Difficulty: ).*(?=">)')
    # Extract the problem description, removing HTML tags
    local description=$(echo "$problem_page" | grep -oP '(?<=<div class="problem-statement">).*(?=</div>)' | sed 's/<[^>]*>//g')
    # Extract the input specification, removing HTML tags
    local input=$(echo "$problem_page" | grep -oP '(?<=<div class="input-specification">).*(?=</div>)' | sed 's/<[^>]*>//g')
    # Extract the output specification, removing HTML tags
    local output=$(echo "$problem_page" | grep -oP '(?<=<div class="output-specification">).*(?=</div>)' | sed 's/<[^>]*>//g')
    # Extract the examples, removing HTML tags
    local examples=$(echo "$problem_page" | grep -oP '(?<=<div class="sample-test">).*(?=</div>)' | sed 's/<[^>]*>//g')

    # Translate title to Chinese using Google Translate API
    local translated_title=$(curl -s "https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=zh-CN&dt=t&q=$(echo $title | sed 's/ /%20/g')" | awk -F'"' '{print $2}')

    # Create markdown content
    local markdown_content="---
title: $title_$translated_title ($difficulty)
date: $(date +%Y-%m-%d)
---

## $title_
## Examples
$examples
## Note
## Parsing
## Core code
"

    # Save to markdown file
    echo "$markdown_content" > "${problem_id}.md"
}

# List of problem URLs
problem_urls=(
    "https://codeforces.com/problemset/problem/344/A"
    # Add more URLs here
)

# Fetch and save each problem
for url in "${problem_urls[@]}"; do
    fetch_problem_details $url
done